<template>
  <div>
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="form.code" />
      </el-form-item>

      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="form.manager" placeholder="请选择部门负责人">
          <!-- <el-option label="小王" value="shanghai" /> -->
          <el-option v-for="item in list " :key="item.id" :label="item.username" :value="item.username" />
        </el-select>
      </el-form-item>

      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="form.introduce" type="textarea" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">
          {{ isEdit? '保存修改' : '确定添加' }}
        </el-button>
        <el-button @click="hCancel">取消</el-button>
      </el-form-item>
    </el-form>

  </div>
</template>
<script>
import { addDepartment, getDepartDetail, editDepartment } from '@/api/department.js'
import { getEmployeeSimple } from '@/api/employee.js'
export default {
  name: 'DeptDialog',
  props: {
    isEdit: { type: Boolean, required: true }, // 是否编辑
    deptId: { type: String, required: true },
    originList: { type: Array, required: true }
  },
  data() {
    // 自定义校验函数
    const validName = (rule, value, callback) => {
      // 当前被占用的部门名字列表  --- 子部门
      let existedNameList = this.originList.filter(item => item.pid === this.deptId).map(item => item.name)
      console.log('当前被占用的部门名字列表', existedNameList)

      if (this.isEdit) {
        // 计算：当前部门的兄弟部门 - 自己
        const cur = this.originList.find(item => item.id === this.deptId)
        const pid = cur.pid
        const bro = this.originList.filter(item => item.pid === pid && item.id !== this.deptId)
        console.log('当前部门的兄弟部门-不包括自己', bro)
        existedNameList = bro.map(item => item.name)
      }

      // if (existedNameList.includes(value)) {
      //   callback(new Error('部门名字：' + value + '被占用了'))
      // } else {
      //   callback()
      // }

      existedNameList.includes(value)
        ? callback(new Error('部门名字：' + value + '被占用了'))
        : callback()
    }

    const validCode = (rule, value, callback) => {
      // 当前被占用的部门编码列表
      let existedList = this.originList.map(item => item.code)

      if (this.isEdit) {
        // 从originList中排除当前项 filter
        // console.log('从originList中排除当前项 filter', this.originList.filter(item => item.id !== this.deptId))
        existedList = this.originList.filter(item => item.id !== this.deptId).map(item => item.code)
      }

      console.log('当前要校验的部门编号是', value, existedList, this.originList)
      if (existedList.includes(value)) {
        // 如果value在 originList中能找到，说明校验失败，这个编号已经被使用了
        callback(new Error('编号' + value + ' 被占用了'))
      } else {
        callback()
      }
    }

    return {
      list: [],
      form: {
        code: '', // 部门编码，同级部门不可重复
        introduce: '', // 介绍
        manager: '', // 负责人名称
        name: '', // 部门名称
        pid: '' // 父级部门ID
      },
      rules: {
        name: [
          { required: true, message: '部门名字不能为空', trigger: 'blur' },
          { min: 1, max: 10, message: '名字1-10之间', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '编码不能为空', trigger: 'blur' },
          { min: 1, max: 10, message: '编码1-10之间', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '负责人不能为空', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '介绍不能为空', trigger: 'blur' },
          { min: 1, max: 300, message: '介绍1-300之间', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    // deptId: function(newVal, oldVal) {
    //   console.log('deptId变化了', newVal, oldVal)
    //   this.loadDepartmentById()
    // }
    // 监听的内容:function(新值，旧值){
    //   // 逻辑
    // }
    // 监听的内容:{
    //   handler：function(新值，旧值){
    //   //   // 逻辑
    //   },
    //   immediate: true | false，
    //   deep: true | false

    // }
  },
  created() {
    this.loadEmployeeSimple()
    // 如果是编辑
    // 发请求获取当前部门的详情数据
    if (this.isEdit) {
      this.loadDepartmentById()
    }
  },
  methods: {
    // 给父组件调用
    resetForm() {
      // 重置表单
      console.log('重置表单')
      // 1. 清空表单的信息
      // 2. 删除校验的痕迹
      this.$refs.form.resetFields()
    },
    // 用户点击 了取消
    hCancel() {
      // 通知父去关闭弹层
      this.$emit('close')
    },
    async loadDepartmentById() {
      console.log('this.deptId', this.deptId)
      const res = await getDepartDetail(this.deptId)
      console.log('发请求获取当前部门的详情数据', res)
      // 数据回填
      this.form = res.data
    },
    async loadEmployeeSimple() {
      const res = await getEmployeeSimple()
      this.list = res.data
    },
    async doAdd() {
      const res = await addDepartment({
        code: this.form.code,
        introduce: this.form.introduce,
        manager: this.form.manager,
        name: this.form.name,
        pid: this.deptId
      })
      console.log(res)
      // 通知父组件更新
      this.$emit('success')
    },

    async doEdit() {
      const res = await editDepartment(this.form)
      console.log(res)
      // 通知父组件更新
      this.$emit('success')
    },
    onSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.isEdit ? this.doEdit() : this.doAdd()
        }
      })
      // todo 表单校验
      // if (this.isEdit) { // 做编辑
      //   this.doEdit()
      // } else { // 做添加
      //   this.doAdd()
      // }
    }
  }
}
</script>
